package com.nuc.iblog.timetask;

import com.nuc.iblog.entity.Article;
import com.nuc.iblog.jpa.ArticleJpa;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Component
@Transactional
@EnableScheduling
public class RedisTimeTask {
    private Logger logger = LoggerFactory.getLogger(RedisTimeTask.class);
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ArticleJpa articleJpa;

    @Scheduled(fixedDelay = 10000)
    public void TaskfixedDelay(){
        List<Article> list=articleJpa.findAll();
        List<String> keys=new ArrayList<String>();
        for(Article article:list){
            keys.add(String.valueOf(article.getAid()));
        }

        flushloves(keys);
        logger.info("redis 定时刷入任务");
    }

    public void flushloves(List<String> keys){
        for(String key:keys){
            try {
                String s=stringRedisTemplate.opsForValue().get(key);
                Article article=articleJpa.getOne(Integer.parseInt(key));
                article.setLove(Integer.parseInt(s));
                articleJpa.save(article);
            }
            catch (Exception e){
                logger.info("redis出错啦");
            }
        }
    }
}
